from pathlib import Path
from PIL import Image


def compress_image(image_path, quality):
    try:
        img = Image.open(image_path)
        exif_data = img.info.get('exif')  # 保留原本的EXIF信息
        if img.width > 3500:  # 压缩宽度大于3500px的图片尺寸
            new_size = (int(img.width * 0.6), int(img.height * 0.6))
            img = img.resize(new_size, resample=Image.LANCZOS)
            print("尺寸已压缩至60%")
        img_compressed = img.copy()  # 压缩并保存图片
        img_compressed.save(image_path, "JPEG", quality=quality, optimize=True, exif=exif_data,
                            icc_profile=img.info.get('icc_profile'))
        img_compressed.thumbnail((1, 1))  # 不保留缩略图
        img.close()
        img_compressed.close()
    except Exception as e:
        print(f"处理文件 {image_path} 时发生错误：{str(e)}")


root_path = Path(r'E:\手机备份\DCIM\Camera')
for path in root_path.glob('*.jpg'):
    if not path.name.startswith('IMG'):  # 如果文件名不以'IMG'开头，则跳过
        continue
    if path.stat().st_size / (1024 * 1024) < 2:  # 如果文件小于2MB
        continue
    elif 2 <= path.stat().st_size / (1024 * 1024) < 5:  # 如果文件大于2MB且小于5MB
        print(path.name, "80%")
        compress_image(path, 80)  # 压缩为JPEG80%
    else:  # 如果文件大于等于5MB
        print(path.name, "70%")
        compress_image(path, 70)  # 压缩为JPEG70%
